package com.woniuxy.portal.controller;

import java.math.BigDecimal;

import com.google.common.collect.Lists;

import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.woniuxy.portal.common.Result;
import com.woniuxy.portal.common.constant.RedisConstant;
import com.woniuxy.portal.model.vo.CardVo;
import com.woniuxy.portal.model.vo.CartItemVo;
import com.woniuxy.portal.service.ICartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer;

@RestController
@RequestMapping("/cart")
public class CartController {
    @Autowired
    private ICartService cartService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 商品添加到购物车
     */
    @PostMapping("/add/{bookId}")
    public Result addCart(
            @PathVariable("bookId") Long bookId,
            @RequestHeader("Authorization") String token) {
        // 处理token
        token = token.replace("Bearer ", "");
        JWT jwt = JWTUtil.parseToken(token);
        Number userId = (Number) jwt.getPayload("userId");
        // 调用Service，实现商品添加到购物车的逻辑处理
        cartService.addCart(userId.longValue(), bookId);
        return Result.ok();
    }

    /**
     * 我的购物车，查询Redis
     */
    @GetMapping("/mycart")
    public Result mycart(@RequestHeader("Authorization") String token) {
        token = token.replace("Bearer ", "");
        JWT jwt = JWTUtil.parseToken(token);
        Number userId = (Number) jwt.getPayload("userId");

        // 从Redis中获取hash数据USER_CART_PREFIX
        Map<String, String> entries = redisTemplate.opsForHash().entries(RedisConstant.USER_CART_PREFIX + userId);
        // 封装从Redis中获取的所有购物项
        List<CartItemVo> cartItemVos = new ArrayList<>();
        // 保存购物车商品总价
        BigDecimal totalPrice = new BigDecimal("0");
        // 遍历集合
        for (Map.Entry<String, String> entry : entries.entrySet()) {
            // key 图书id
            // value 是 CartItemVo转换后的json字符串； 现在需要json-->CartItemVo
            CartItemVo cartItemVo = JSONUtil.toBean(entry.getValue(), CartItemVo.class);
            cartItemVos.add(cartItemVo);
            // 累加小计
            totalPrice = totalPrice.add(cartItemVo.getSumPrice());
        }
        // 购物车对象
        CardVo cardVo = new CardVo();
        cardVo.setCartItemVos(cartItemVos);
        cardVo.setTotalPrice(totalPrice);
        cardVo.setUserId(userId.intValue());

        return Result.ok(cardVo);
    }

    /**
     * 购物车修改数量
     */
    @PostMapping("/changeCartNum")
    public Result changeCartNum(@RequestBody CartItemVo cartItemVo, @RequestHeader("Authorization") String token) {
        // 根据user_cart_userId这个key，加上bookId, 从Redis获取carItemVo的json存储字符串

        token = token.replace("Bearer ", "");
        JWT jwt = JWTUtil.parseToken(token);
        Number userId = (Number) jwt.getPayload("userId");

        // 从redis获取购物项
        String userKey = RedisConstant.USER_CART_PREFIX + userId.toString();
        String json = (String) redisTemplate.opsForHash().get(userKey, cartItemVo.getId().toString());
        // json---> cartItemVo
        CartItemVo itemVo = JSONUtil.toBean(json, CartItemVo.class);
        // 设置购买数量
        itemVo.setBuycount(cartItemVo.getBuycount());
        // 重新计算小计 = 单价 * 数量
        itemVo.setSumPrice(itemVo.getPrice().multiply(new BigDecimal(itemVo.getBuycount())));

        // 将修改后的对象存入Redis:  用户ID  图书ID  CartItemVo的json
        redisTemplate.opsForHash().put(userKey, itemVo.getId().toString(), JSONUtil.toJsonStr(itemVo));

        return Result.ok();
    }

    /**
     * 购物车删除
     */
    @PostMapping("/deleteById")
    public Result deleteById(@RequestBody CartItemVo cartItemVo, @RequestHeader("Authorization") String token) {
        token = token.replace("Bearer ", "");
        JWT jwt = JWTUtil.parseToken(token);
        Number userId = (Number) jwt.getPayload("userId");
        // 删除
        redisTemplate.opsForHash().delete(RedisConstant.USER_CART_PREFIX + userId,String.valueOf(cartItemVo.getId()));
        return Result.ok();
    }

    /**
     * 在calc.html结算页面，查询显示结算明细项目
     */
    @PostMapping("/calc")
    public Result calc(@RequestBody Long[] ids,@RequestHeader("Authorization") String token) {
        // 从token中获取用户id
        token = token.replace("Bearer ", "");
        JWT jwt = JWTUtil.parseToken(token);
        Number userId = (Number) jwt.getPayload("userId");

        List<CartItemVo> cartItemVos = new ArrayList<>();
        BigDecimal totalPrice = new BigDecimal("0");

        // 遍历ids
        for (Long id : ids) {
            String cartItemVoString = (String) redisTemplate.opsForHash().get(RedisConstant.USER_CART_PREFIX+userId.intValue(), id.toString());
            // 转换
            CartItemVo cartItemVo = JSONUtil.toBean(cartItemVoString, CartItemVo.class);
            cartItemVos.add(cartItemVo);
            // 累计
            totalPrice = totalPrice.add(cartItemVo.getSumPrice());
        }

        CardVo cardVo = new CardVo();
        cardVo.setCartItemVos(cartItemVos);
        cardVo.setTotalPrice(totalPrice);

        return Result.ok(cardVo);
    }

}









